import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface User {
  id: number;
  familyId: number;
  role: 'PARENT' | 'GUARDIAN';
  nickname?: string;
}

export interface Baby {
  id: number;
  nickname: string;
  birthday: string;
  gender: 'M' | 'F';
  avatarUrl?: string;
  createdAt: string;
}

export const useUserStore = defineStore('user', () => {
  // 当前用户信息
  const currentUser = ref<User | null>(null);
  
  // 当前家庭的所有宝宝
  const familyBabies = ref<Baby[]>([]);
  
  // 当前选择的宝宝ID
  const currentBabyId = ref<number | null>(null);
  
  // 计算属性
  const currentBaby = computed(() => {
    if (!currentBabyId.value) return null;
    return familyBabies.value.find(baby => baby.id === currentBabyId.value) || null;
  });
  
  const isLoggedIn = computed(() => !!currentUser.value);
  
  // 设置用户信息
  function setUser(user: User) {
    currentUser.value = user;
  }
  
  // 设置家庭宝宝列表
  function setFamilyBabies(babies: Baby[]) {
    familyBabies.value = babies;
    // 如果有宝宝且没有选择，选择第一个
    if (babies.length > 0 && !currentBabyId.value) {
      currentBabyId.value = babies[0].id;
    }
  }
  
  // 切换当前宝宝
  function switchBaby(babyId: number) {
    currentBabyId.value = babyId;
  }
  
  // 登出
  function logout() {
    currentUser.value = null;
    familyBabies.value = [];
    currentBabyId.value = null;
  }
  
  // 从localStorage恢复用户状态
  async function restoreUserState() {
    const token = localStorage.getItem('auth_token');
    if (token) {
      console.log('检测到token，尝试恢复用户状态');
      try {
        // 从API获取用户信息
        const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'}/api/auth/me`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.ok) {
          const userData = await response.json();
          currentUser.value = userData.user;
          console.log('恢复用户状态:', userData.user);
          return true;
        } else {
          console.log('token无效，清除本地存储');
          localStorage.removeItem('auth_token');
          return false;
        }
      } catch (error) {
        console.error('恢复用户状态失败:', error);
        localStorage.removeItem('auth_token');
        return false;
      }
    }
    return false;
  }
  
  return {
    currentUser,
    familyBabies,
    currentBabyId,
    currentBaby,
    isLoggedIn,
    setUser,
    setFamilyBabies,
    switchBaby,
    logout,
    restoreUserState
  };
});
